package com.youyiwen.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.youyiwen.Bean.ChatList;
import com.youyiwen.Bean.Message;
import com.youyiwen.Bean.User;
import com.youyiwen.Mapper.ChatListMapper;
import com.youyiwen.Mapper.MessageMapper;
import com.youyiwen.Mapper.UserMapper;
import com.youyiwen.Service.ChatListService;
import com.youyiwen.Service.MessageService;
import com.youyiwen.dto.ChatListDTO;
import com.youyiwen.dto.MessageDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author: zhaoyang
 * @Date: 2021/04/21
 */
@Controller
public class ChatController {
    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private MessageService messageService;

    @Autowired
    private ChatListMapper chatListMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ChatListService chatListService;

    //
//    @GetMapping("/userCenter/chat")
//    public String communicatePage(Model model, HttpSession session) {
//        User user = (User) session.getAttribute("loginUser");
//        String me = user.getUserName();
//        List<ChatListDTO> list = chatListService.list(me);
//        model.addAttribute("chatLists", list);
//        return "chat";
//    }


    @ResponseBody
    @GetMapping("/userCenter/chat/{receiver}")
    public String chatWithOthers(@PathVariable("receiver") String receiver,
                                    Model model, HttpSession session)  {
        //搜索用户的聊天状态
        User user = (User) session.getAttribute("loginUser");
        String sender = user.getUserName();
//        List<ChatListDTO> chatLists = chatListService.list(sender);
//        model.addAttribute("chatLists", chatLists);
//
//        if (userMapper.selectUserByName(receiver)==null){
//            model.addAttribute("noUser","noUser");
//            return "";
//        }

        //更改消息数的时候，receiver是发送者，而sender是接收者
//        messageMapper.updateMessageCount(receiver,sender);
        //查找属于sender的两人会话
        List<MessageDTO> list = messageService.messagesList(sender, receiver, sender);
        JSONArray array= JSONArray.parseArray(JSON.toJSONString(list));
        return array.toJSONString();
    }


    @ResponseBody
    @PostMapping(value = "/chat/{receiver}")
    public String sendMassage(@PathVariable("receiver") String receiver,
                              @RequestParam String content,
                              HttpSession session) {
        MessageDTO dto = new MessageDTO();
        User user = (User) session.getAttribute("loginUser");
        String sender = user.getUserName();
        Long current;
        //创建两个人的消息
        for (int i = 1; i <= 2; i++) {
            Message msg = new Message();
            current = System.currentTimeMillis();
            String id = sender + "-" + receiver + "-" + current;
            msg.setId(id);
            msg.setSender(sender);
            msg.setReceiver(receiver);
            msg.setHasRead(1);
            msg.setContent(content);
            msg.setGmtCreate(current);
            if (i == 1) {
                //发送者的消息直接已读
                msg.setForUser(sender);
                User senderUser = userMapper.selectUserByName(sender);
                dto.setSender(senderUser);
                dto.setMessage(msg);
            } else {
                //接收者只有在点击后才已读
                msg.setForUser(receiver);
                msg.setHasRead(0);
                User receiveUser = userMapper.selectUserByName(receiver);
                dto.setSender(receiveUser);
            }
            //插入消息
            messageMapper.insertMsg(msg);
        }

        if (chatListMapper.selectChatId(sender, receiver) == null)
        //插入到会话列表
        {
            for (int i = 1; i <=2 ; i++) {
                ChatList chatList = new ChatList();
                current = System.currentTimeMillis();
                chatList.setId(sender + current);
                chatList.setLastReplyTime(current);
                chatList.setMsgCount(i-1);
                //循环为两个人的对话赋值
                if (i == 1){
                    chatList.setMe(sender);
                    chatList.setOthers(receiver);

                }
                else{
                    chatList.setMe(receiver);
                    chatList.setOthers(sender);
                }
                chatListMapper.insertChatList(chatList);
            }
        }else {
            current = System.currentTimeMillis();
            chatListMapper.incMsgCount(receiver,sender);
            chatListMapper.updateLastReplyTime(sender,receiver,current);
        }

        String json = JSON.toJSONString(dto);
        return json;
    }
}
